package com.atguigu.filter;

import com.atguigu.util.JDBCUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @ Author:任留辉
 * @ Description:
 * @ Date:Created in 23:13 2021/3/22 0022
 */
public class TransactionFilter extends HttpFilter {
    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        Connection connection = null;
        try {
            connection = JDBCUtils.getConnection();
            //关闭mysql的自动提交事务
            connection.setAutoCommit(false);
            //放行，表示当前实现的整个功能的过程
            chain.doFilter(request, response);
            //没有异常，则提交
            connection.commit();
        } catch (Exception e) {
            //有异常，则回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        } finally {
            JDBCUtils.closeConnection(connection);
        }
    }

}
